const studentSelect = document.getElementById("student-select");
let studentChart;
let studentCode;

// 初始化下拉框
function populateStudentSelect() {
    studentSelect.innerHTML = '';
    Object.keys(studentDetails).forEach(code => {
        const option = document.createElement("option");
        option.value = code;
        option.textContent = studentDetails[code][0].stu_name;
        studentSelect.appendChild(option);
    });
}

// 获取学生的有效数据
function getStudentData() {
    return studentDetails[studentCode]
        .filter(stu => stu.score !== null)
        .map((stu, index, arr) => {
            // 计算rankDiff，当前项的rank减去上一项的rank
            const rankDiff = index === 0 ? null : arr[index - 1].rank - stu.rank;
            // 返回新的对象，包含所需的字段
            return {
                stu_name: stu.stu_name,
                stu_code: stu.stu_code,
                examCode: stu.exam_code,
                rank: stu.rank,
                score: stu.score,
                avgScore: examDetails[stu.exam_code].avg_score,
                grade: stu.grade,
                rankDiff: rankDiff
            };
        });
}

// 更新表格内容和折线图（根据选择的学生）
function renderGradeTable() {
    const tableBody = document.getElementById('table-body');
    tableBody.innerHTML = ''; // 清空现有表格内容

    // 动态渲染表格数据
    const data = getStudentData(studentCode)
    if (data) {
        data.forEach(item => {
            const row = document.createElement('tr');
            const examCodeCell = document.createElement('td');
            examCodeCell.textContent = item.examCode;
            const gradeCell = document.createElement('td');
            gradeCell.textContent = item.grade;
            const rankCell = document.createElement('td');
            const rankDiffHtml = item.rankDiff >= 0 ? `<span class="arrow-up">↑${item.rankDiff}</span>` : `<span class="arrow-down">↓${item.rankDiff}</span>`;
            rankCell.innerHTML = `
            <div>
                <span class="rank-tag">${item.rank}</span>
                ${item.rankDiff == null ? "" : rankDiffHtml}
            </div>
            `;
            row.appendChild(examCodeCell);
            row.appendChild(gradeCell);
            row.appendChild(rankCell)
            tableBody.appendChild(row);
        });
    }
}

// 渲染图表
function renderChart() {
    const data = getStudentData(studentCode);
    const labels = data.map(item => item.examCode);
    const ranks = data.map(item => item.rank);
    const avgScores = data.map(item => item.avgScore);
    const scores = data.map(item => item.score);
    // const grades = data.map(item => item.grade);

    if (studentChart) {
        studentChart.destroy();
    }

    const ctx = document.getElementById("rankingChart").getContext("2d");

    studentChart = new Chart(ctx, {
        type: "bar",
        data: {
            labels: labels, // x 轴标签
            datasets: [
                {
                    label: "分数",
                    data: scores,
                    barPercentage: 0.5,
                    backgroundColor: 'rgba(0, 128, 0, 0.2)',
                    // borderColor: 'rgba(0, 128, 0, 1)',
                    // borderWidth: 1,
                    type: 'bar', // 指定为柱形图
                    yAxisID: 'y-axis-score', // 指定y轴ID
                    datalabels: { // 为第二个数据集设置数据标签选项
                        color: 'rgb(0, 128, 0,1)',
                        anchor: 'end',
                        align: 'top',
                        formatter: (value) => {
                            return value;
                        }
                    }
                },
                {
                    label: "Rank",
                    data: ranks,
                    borderColor: 'rgba(255, 99, 132, 0.5)',
                    fill: false,
                    tension: 0.4,
                    pointStyle: 'circle',
                    type: 'line',
                    yAxisID: 'y-axis-rank',
                    datalabels: { // 为第二个数据集设置数据标签选项
                        color: 'rgba(255, 99, 132, 1)',
                        anchor: 'center',
                        align: 'top',
                        formatter: (value) => {
                            return value;
                        }
                    }
                },
                {
                    label: "班级平均分",
                    data: avgScores,
                    borderColor: "rgba(255, 165, 0,0.4)",
                    fill: false,
                    tension: 0.4,
                    pointStyle: false,
                    type: 'line',
                    yAxisID: 'y-axis-score',
                    datalabels: {
                        display: false
                    }
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                'y-axis-score': {
                    min: 0,
                    max: 100,
                    type: 'linear',
                    position: 'left',
                    ticks: {
                        beginAtZero: true
                    },
                },
                'y-axis-rank': {
                    min: 1,
                    type: 'linear',
                    display: true,
                    position: 'right',
                    ticks: {
                        beginAtZero: true
                    },
                    grid: {
                        display: false // 不显示网格线
                    },
                    reverse: true // 反转比例
                }
            },
        },
        plugins: [ChartDataLabels] // 启用插件
    });
}

// 事件监听
studentSelect.addEventListener("change", (e) => {
    studentCode = e.target.value
    renderGradeTable();
    renderChart();
});